package com.lalifa.googledate.ui.activity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.RectF
import android.graphics.drawable.GradientDrawable
import android.os.Handler
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.ScrollView
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.ViewCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.blankj.utilcode.util.LogUtils
import com.drake.brv.BindingAdapter
import com.drake.net.utils.scopeNetLife
import com.gjiazhe.scrollparallaximageview.ScrollParallaxImageView
import com.gjiazhe.scrollparallaximageview.parallaxstyle.VerticalMovingStyle
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.lalifa.base.BaseActivity
import com.lalifa.base.BaseApplication
import com.lalifa.ext.showTipDialog
import com.lalifa.extension.PATTERN_DATE
import com.lalifa.extension.PATTERN_HOUR_MINUTE
import com.lalifa.extension.format
import com.lalifa.extension.gone
import com.lalifa.extension.invisible
import com.lalifa.extension.load
import com.lalifa.extension.onClick
import com.lalifa.extension.start
import com.lalifa.extension.toast
import com.lalifa.extension.visible
import com.lalifa.googledate.R
import com.lalifa.googledate.api.AddEvent
import com.lalifa.googledate.api.CalendarUp
import com.lalifa.googledate.api.CountryBean
import com.lalifa.googledate.api.CountryListBean
import com.lalifa.googledate.api.EventInfo
import com.lalifa.googledate.api.EventListBean
import com.lalifa.googledate.api.EventModel
import com.lalifa.googledate.api.EventPositionBean
import com.lalifa.googledate.api.HolidayUp
import com.lalifa.googledate.api.MessageEvent
import com.lalifa.googledate.api.MonthModel
import com.lalifa.googledate.api.UserBean
import com.lalifa.googledate.api.api.InitNet
import com.lalifa.googledate.api.loginApi
import com.lalifa.googledate.databinding.ActivityMainBinding
import com.lalifa.googledate.ui.MApplication
import com.lalifa.googledate.ui.activity.set.SetOneActivity
import com.lalifa.googledate.ui.activity.type.TypeManage
import com.lalifa.googledate.ui.adapter.YearPageAdapter
import com.lalifa.googledate.ui.adapter.calendarAdapter
import com.lalifa.googledate.ui.dialog.addTaskDialog
import com.lalifa.googledate.ui.dialog.settingDialog
import com.lalifa.googledate.ui.dialog.showActDialog
import com.lalifa.googledate.ui.dialog.showAppDialog
import com.lalifa.googledate.ui.dialog.showHelpDialog
import com.lalifa.googledate.ui.dialog.showHolidayDialog
import com.lalifa.googledate.ui.weekview.DateTimeInterpreter
import com.lalifa.googledate.ui.weekview.MonthLoader
import com.lalifa.googledate.ui.weekview.WeekView
import com.lalifa.googledate.ui.weekview.WeekViewEvent
import com.lalifa.googledate.util.CalendarUtils
import com.lalifa.googledate.util.CalendarUtils.ACTIVITY_SHOW
import com.lalifa.googledate.util.CalendarUtils.BIRTHDAY_SHOW
import com.lalifa.googledate.util.CalendarUtils.CALENDARS_LIST
import com.lalifa.googledate.util.CalendarUtils.CALENDARS_NAME
import com.lalifa.googledate.util.CalendarUtils.changeCalendarSet
import com.lalifa.googledate.util.CalendarUtils.deleteCalendarEvent
import com.lalifa.googledate.util.MUtils.Companion.getDeviceHeight
import com.lalifa.googledate.util.MUtils.Companion.getDevicewidth
import com.lalifa.googledate.util.MUtils.Companion.getNavigationHeight
import com.lalifa.googledate.util.MUtils.Companion.getStatusBarHeight
import com.lalifa.googledate.util.MonthChange
import com.lalifa.googledate.util.Tool
import com.lalifa.googledate.util.UserManager
import com.lalifa.googledate.widget.MyAppBarBehavior
import com.lalifa.googledate.widget.MyRecyclerView
import com.lalifa.utils.GsonUtil
import com.lalifa.utils.LiveDataBus
import com.lalifa.utils.SPUtil
import com.lalifa.utils.UIKit
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration
import org.joda.time.DateTimeZone
import org.joda.time.Days
import org.joda.time.LocalDate
import org.joda.time.LocalDateTime
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
import kotlin.math.abs

open class MainActivity : BaseActivity<ActivityMainBinding>(),
    MyRecyclerView.AppBarTracking, WeekView.EventClickListener,
    MonthLoader.MonthChangeListener, WeekView.EventLongPressListener,
    WeekView.EmptyViewLongPressListener, WeekView.ScrollListener {
    override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)
    private val monthreSource = intArrayOf(
        R.mipmap.c1,
        R.mipmap.c2,
        R.mipmap.c3,
        R.mipmap.c4,
        R.mipmap.c5,
        R.mipmap.c6,
        R.mipmap.c7,
        R.mipmap.c8,
        R.mipmap.c9,
        R.mipmap.c10,
        R.mipmap.c11,
        R.mipmap.c12
    )
    private var expandedfirst = 0
    private var mAppBarOffset = 0
    private var mAppBarIdle = true
    private var isappbarclosed = true
    private var isgivepermission = false
    private var mIsExpanded = false
    private var mycolor = 0
    private var month = 0
    private var lasttime: Long = 0
    private var mAppBarMaxOffset = 0
    private var lastchangeindex = -1
    private var eventalllist = arrayListOf<EventModel>()
    private var montheventlist: java.util.HashMap<LocalDate, EventInfo>? = null
    private var indextrack: ArrayList<EventPositionBean> = arrayListOf()
    private var eventview: View? = null
    private var fullview: View? = null
    private var u: UserBean? = null
    private var calendarAdapter: BindingAdapter? = null

    companion object {
        var topspace = 0
        var lastdate: LocalDate = LocalDate.now()
        var eventList = arrayListOf<EventListBean>()

        @SuppressLint("StaticFieldLeak")
        var mNestedView: MyRecyclerView? = null

        @SuppressLint("StaticFieldLeak")
        var weekviewcontainer: ScrollView? = null

        @SuppressLint("StaticFieldLeak")
        var mWeekView: WeekView? = null
    }

    @SuppressLint("SetTextI18n", "ClickableViewAccessibility", "RtlHardcoded")
    override fun initView() {
        binding.apply {
            weekviewcontainer = weekViewContainer
            mWeekView = weekView
            mNestedView = nestedView
            closebtn.setOnClickListener { closeClick() }
            calender.setPadding(0, getStatusBarHeight(), 0, 0)
            monthviewpager.offscreenPageLimit = 1
            monthviewpager.addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(i: Int, v: Float, i1: Int) {}
                override fun onPageSelected(i: Int) {
                    if (!monthviewpager.isVisible) return
                    if (isAppBarClosed()) {
                        val localDate = LocalDate()
                        val monthPageAdapter =
                            monthviewpager.adapter as MonthPageAdapter?
                        val monthModel = monthPageAdapter!!.monthModels[i]
                        val year =
                            if (monthModel.year == localDate.year) "" else
                                monthModel.year.toString()
                        monthName.text = monthModel.monthnamestr + " " + year
                        lastdate = LocalDate(monthModel.year, monthModel.month, 1)
                        // EventBus.getDefault().post(new MessageEvent(new LocalDate(monthModel.getYear(),monthModel.getMonth(),1)));
                        // if (monthChangeListner!=null)monthChangeListner.onmonthChange(myPagerAdapter.monthModels.get(position));
                    } else {
                       // calender.currentmonth = i
                    }
                }

                override fun onPageScrollStateChanged(i: Int) {}
            })
            yearviewpager.offscreenPageLimit = 1
            yearviewpager.addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(i: Int, v: Float, i1: Int) {}
                override fun onPageSelected(i: Int) {
                    if (!yearviewpager.isVisible) return
                    if (isAppBarClosed()) {
                        monthName.text = (2000 + i).toString() + ""
                        // EventBus.getDefault().post(new MessageEvent(new LocalDate(monthModel.getYear(),monthModel.getMonth(),1)));
                        // if (monthChangeListner!=null)monthChangeListner.onmonthChange(myPagerAdapter.monthModels.get(position));
                    } else {
                        // calendarView.setCurrentmonth(i);
                    }
                }

                override fun onPageScrollStateChanged(i: Int) {}
            })
            //  setMargins(mNestedView,0,0,0,getnavigationHeight());
            mNestedView!!.setAppBarTracking(this@MainActivity)
            val linearLayoutManager = LinearLayoutManager(this@MainActivity)
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            mNestedView!!.layoutManager = linearLayoutManager
            val dateAdapter = DateAdapter()
            mNestedView!!.adapter = dateAdapter
            val headersDecor = StickyRecyclerHeadersDecoration(dateAdapter)
            mNestedView!!.addItemDecoration(headersDecor)
            calender.setMonthChangeListner { monthModel ->
                val localDate = LocalDate()
                val year =
                    if (monthModel.year == localDate.year) "" else monthModel.year.toString()
                monthName.text = monthModel.monthnamestr + " " + year
                if (weekviewcontainer!!.isVisible) {
                    val today = Calendar.getInstance()
                    today[Calendar.DAY_OF_MONTH] = 1
                    today[Calendar.MONTH] = monthModel.month - 1
                    today[Calendar.YEAR] = monthModel.year
                    mWeekView!!.goToDate(today)
                }
            }
            isgivepermission = true
            mIsExpanded = false
            appBar.setExpanded(false, false)
            toolbar.setPadding(0, getStatusBarHeight(), 0, 0)
            if (monthviewpager.isVisible || yearviewpager.isVisible) {
                val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
                (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(false)
                appBar.elevation = 0f
                arrowImageView.invisible()
            } else {
                val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
                (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(true)
                appBar.elevation = 20f
                arrowImageView.visible()
            }
            mNestedView!!.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                var llm = mNestedView!!.layoutManager as LinearLayoutManager?
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (mAppBarOffset != 0 && isappbarclosed && newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                        calender.setCurrentmonth(dateAdapter.getEventAllList()[expandedfirst].localDate)
                        calender.adjustheight()
                        mIsExpanded = false
                        appBar.setExpanded(false, false)
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (isappbarclosed) {
                        var pos = llm!!.findFirstVisibleItemPosition()
                        val view = llm!!.findViewByPosition(pos)
                        var currentmonth = dateAdapter.getEventAllList()[pos].localDate.monthOfYear
                        if (dateAdapter.getEventAllList()[pos].type == 1) {
                            if (dy > 0 && abs(view!!.top) > 100) {
                                if (month != currentmonth) {
                                    LiveDataBus.get().with("monthChangeEvent").value = MonthChange(
                                        dateAdapter.getEventAllList()[pos].localDate, dy
                                    )
                                }
                                month = currentmonth
                                lastdate = dateAdapter.getEventAllList()[pos].localDate
                                expandedfirst = pos
                            } else if (dy < 0 && abs(view!!.top) < 100 && pos - 1 > 0) {
                                pos--
                                currentmonth =
                                    dateAdapter.getEventAllList()[pos].localDate.monthOfYear
                                if (month != currentmonth) {
                                    LiveDataBus.get().with("monthChangeEvent").value = MonthChange(
                                        dateAdapter.getEventAllList()[pos].localDate, dy
                                    )
                                }
                                month = currentmonth
                                lastdate = dateAdapter.getEventAllList()[pos].localDate.dayOfMonth()
                                    .withMaximumValue()
                                expandedfirst = pos
                            }
                        } else {
                            lastdate = dateAdapter.getEventAllList()[pos].localDate
                            expandedfirst = pos
                        }
                    }
                    super.onScrolled(recyclerView, dx, dy)
                }
            })
            setSupportActionBar(toolbar)
            val ab = supportActionBar
            if (ab != null) {
                supportActionBar!!.setDisplayShowTitleEnabled(false)
                supportActionBar!!.setDisplayHomeAsUpEnabled(true)
                supportActionBar!!.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp)
            }
            appBar.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
                if (mAppBarOffset != verticalOffset) {
                    mAppBarOffset = verticalOffset
                    mAppBarMaxOffset = -appBar.totalScrollRange
                    //calendarView.setTranslationY(mAppBarOffset);
                    //calendarView.setLayoutParams(new CollapsingToolbarLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,500));
                    val totalScrollRange = appBarLayout.totalScrollRange
                    val progress = (-verticalOffset).toFloat() / totalScrollRange.toFloat()
                    if ((monthviewpager.isGone || yearviewpager.isGone) && mNestedView!!.isVisible)
                        appBar.elevation = 20 + 20 * abs(1 - progress)
                    if (weekviewcontainer!!.isVisible) {
                        appBar.elevation = 20 - 20 * abs(progress)
                    }
                    if (abs(progress) > 0.45) {
                        val params = myshadow.layoutParams
                        params.height =
                            (resources.getDimensionPixelSize(R.dimen.fourdp) * abs(progress)).toInt()
                        myshadow.layoutParams = params
                    }
                    arrowImageView.rotation = progress * 180
                    mIsExpanded = verticalOffset == 0
                    mAppBarIdle = mAppBarOffset >= 0 || mAppBarOffset <= mAppBarMaxOffset
                    //    val alpha = -verticalOffset.toFloat() / totalScrollRange
                    if (mAppBarOffset == -appBarLayout.totalScrollRange) {
                        isappbarclosed = true
                        setExpandAndCollapseEnabled(false)
                    } else {
                        setExpandAndCollapseEnabled(true)
                    }
                    if (mAppBarOffset == 0) {
                        expandedfirst = linearLayoutManager.findFirstVisibleItemPosition()
                        val p = linearLayoutManager.findViewByPosition(
                            linearLayoutManager.findFirstVisibleItemPosition()
                        )
                        if (mNestedView!!.isVisible && p != null) {
                            topspace = p.top
                        }
                        if (isappbarclosed) {
                            isappbarclosed = false
                            mNestedView!!.stopScroll()
                            //linearLayoutManager.scrollToPositionWithOffset(expandedfirst,0);
                            calender.setCurrentmonth(lastdate)
                        }
                    }
                }
            }
            monthName.setOnClickListener(
                View.OnClickListener { //
                    if (monthviewpager.isVisible || yearviewpager.isVisible) return@OnClickListener
                    mIsExpanded = !mIsExpanded
                    mNestedView!!.stopScroll()
                    appBar.setExpanded(mIsExpanded, true)
                })
            /////////////////weekview implemention/////
            mWeekView!!.setshadow(myshadow)
            mWeekView!!.setfont(
                ResourcesCompat.getFont(
                    this@MainActivity,
                    R.font.googlesans_regular
                ), 0
            )
            mWeekView!!.setfont(ResourcesCompat.getFont(this@MainActivity, R.font.googlesansmed), 1)
            mWeekView!!.setOnEventClickListener(this@MainActivity)
            mWeekView!!.monthChangeListener = this@MainActivity
            mWeekView!!.eventLongPressListener = this@MainActivity
            mWeekView!!.emptyViewLongPressListener = this@MainActivity
            mWeekView!!.scrollListener = this@MainActivity
            setupDateTimeInterpreter(false)
            u = UserManager.get()
            showUser(u)
            calendarAdapter = calendarList.calendarAdapter().apply {
                R.id.imCalendar.onClick {
                    start(TypeManage::class.java) {
                        putExtra("list", CALENDARS_LIST)
                    }
                }
            }
            initEvent()
            getEventList()
        }
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    private fun initEvent() {
        LiveDataBus.get().with("msgEvent", MessageEvent::class.java).observe(this) { event ->
            val previous: Int = lastchangeindex
            if (previous != -1) {
                var totalremove = 0
                for (k in 1..3) {
                    if (eventalllist[previous].eventname.equals("eventView") ||
                        eventalllist[previous].eventname.equals("click")
                    ) {
                        totalremove++
                        eventalllist.removeAt(previous)
                    }
                }
                mNestedView!!.adapter!!.notifyDataSetChanged()
            }
            val linearLayoutManager = mNestedView!!.layoutManager as LinearLayoutManager?
            indextrack.forEach {
                if (it.localDate == event.message) {
                    val type = eventalllist[it.p].type
                    if (type == 0 || type == 2) {
                        lastdate = event.message
                        expandedfirst = it.p
                        topspace = 20
                        lastchangeindex = -1
                    } else {
                        lastdate = event.message
                        var ind = it.p
                        for (i in ind until eventalllist.size) {
                            if (event.message.isBefore(eventalllist[i].localDate)) {
                                ind = i
                                break
                            }
                        }
                        lastchangeindex = ind
//                        val typeSelect = if (eventalllist[ind + 1].type == 200) 200 else 100
//                        if (!eventalllist[ind - 1].eventname.startsWith("eventView")) {
//                            eventalllist.add(
//                                ind, EventModel(
//                                    "eventView", event.message, typeSelect,
//                                    eventalllist[ind - 1].color, event.id
//                                )
//                            )
//                            ind += 1
//                        }
                        expandedfirst = ind
//                        eventalllist.add(
//                            ind, EventModel(
//                                "click", event.message, 1000,
//                                eventalllist[ind].color, event.id
//                            )
//                        )
                        ind += 1
//                        if (!eventalllist[ind].eventname.startsWith("eventView")) {
//                            eventalllist.add(
//                                ind, EventModel(
//                                    "eventView", event.message,
//                                    typeSelect, eventalllist[ind].color, event.id
//                                )
//                            )
//                        }
                        mNestedView!!.adapter!!.notifyDataSetChanged()
                        topspace = 20
                        for (i in lastchangeindex until eventalllist.size) {
                            if (!eventalllist[i].eventname.startsWith("eventView"))
                                it.p = i
                        }
                    }
                    linearLayoutManager?.scrollToPosition(it.p)
                }
            }
//            if (indextrack!!.containsKey(event.message)) {
//
//            } else {
//                var ind = indextrack!![event.message.dayOfWeek().withMinimumValue().minusDays(1)]
//                ind = ind!! + 1
//                for (i in ind!! until eventalllist.size) {
//                    if (event.message.isBefore(eventalllist[i].localDate)) {
//                        ind = i
//                        break
//                    }
//                }
//                lastchangeindex = ind
//                val typeSelect = if (eventalllist[ind + 1].type == 200) 200 else 100
//                if (!eventalllist[ind - 1].eventname.startsWith("eventView")) {
//                    eventalllist.add(
//                        ind, EventModel(
//                            "eventView", event.message,
//                            typeSelect, eventalllist[ind - 1].color, event.id
//                        )
//                    )
//                    ind += 1
//                }
//                expandedfirst = ind
//                eventalllist.add(
//                    ind, EventModel(
//                        "click", event.message,
//                        1000, eventalllist[ind].color, event.id
//                    )
//                )
//                ind += 1
//                if (!eventalllist[ind].eventname.startsWith("eventView")) {
//                    eventalllist.add(
//                        ind, EventModel(
//                            "eventView", event.message,
//                            typeSelect, eventalllist[ind].color, event.id
//                        )
//                    )
//                }
//                mNestedView!!.adapter!!.notifyDataSetChanged()
//                topspace = 20
//                linearLayoutManager!!.scrollToPositionWithOffset(expandedfirst, 20)
//                for (i in lastchangeindex until eventalllist.size) {
//                    if (!eventalllist[i].eventname.startsWith("eventView"))
//                        indextrack!![eventalllist[i].localDate] = i
//                }
//            }
        }
        /**
         * this call when user is scrolling on mNestedView(recyclerview) and month will change
         * or when toolbar top side current date button selected
         */
        LiveDataBus.get().with("monthChangeEvent", MonthChange::class.java)
            .observe(this) { event ->
                if (!isAppBarExpanded()) {
                    binding.apply {
                        val localDate = LocalDate()
                        val year = if (event.message.year == localDate.year) "" else
                            event.message.year.toString()
                        monthName.text = "${event.message.toString("MMMM")} $year"
                        val diff: Long = System.currentTimeMillis() - lasttime
                        val check = diff > 600
                        if (check && event.mdy > 0) {
                            monthName.translationY = 35f
                            arrowImageView.translationY = 35f
                            lasttime = System.currentTimeMillis()
                            monthName.animate().translationY(0f).setDuration(200).start()
                            arrowImageView.animate().translationY(0f).setDuration(200).start()
                        } else if (check && event.mdy < 0) {
                            monthName.translationY = -35f
                            arrowImageView.translationY = -35f
                            lasttime = System.currentTimeMillis()
                            monthName.animate().translationY(0f).setDuration(200).start()
                            arrowImageView.animate().translationY(0f).setDuration(200).start()
                        }
                    }
                }
            }

        LiveDataBus.get().with("addEvent", AddEvent::class.java)
            .observe(this) { event ->
                eventalllist = event.arrayList
                indextrack = event.indexTracker
                if (mNestedView!!.isAttachedToWindow) {
                    mNestedView!!.adapter!!.notifyDataSetChanged()
                }
                val tv = TypedValue()
                if (theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                    val actionBarHeight =
                        TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
                    val monthheight: Int =
                        getDeviceHeight() - actionBarHeight - getNavigationHeight() - getStatusBarHeight()
                    val recyheight =
                        monthheight - resources.getDimensionPixelSize(R.dimen.monthtopspace)
                    val singleitem = (recyheight - 18) / 6
                    binding.apply {
                        //monthviewpager.setAdapter(new MonthViewPagerAdapter(MainActivity.this,event.getMonthModels(),singleitem));
                        monthviewpager.adapter = MonthPageAdapter(
                            supportFragmentManager, event.monthModels, singleitem
                        )
                        monthviewpager.setCurrentItem(
                            calender.calculateCurrentMonth(LocalDate.now()), false
                        )
                        yearviewpager.adapter = YearPageAdapter(supportFragmentManager)
                        yearviewpager.setCurrentItem(LocalDate.now().year % 2000, false)
                    }
                }
                Handler().postDelayed({
                    val localDate = LocalDate()
                    val linearLayoutManager = mNestedView!!.layoutManager as LinearLayoutManager?
                    indextrack.forEach {
                        if (it.localDate == LocalDate.now()) {
                            expandedfirst = it.p
                            topspace = 20
                            linearLayoutManager!!.scrollToPositionWithOffset(it.p, 20)
                            month = localDate.dayOfMonth
                            lastdate = localDate
                            LiveDataBus.get().with("monthChangeEvent").value =
                                MonthChange(localDate, 0)
                        }
                    }
                }, 100)
            }
        LiveDataBus.get().with("calenderList", CalendarUp::class.java)
            .observe(this) { _ ->
                CalendarUtils.upCalendarList(this)
                calendarAdapter!!.models = CALENDARS_LIST
            }
        LiveDataBus.get().with("holidayList", HolidayUp::class.java)
            .observe(this) { _ ->
                getEventList()
            }
    }

    @SuppressLint("SetTextI18n", "RtlHardcoded")
    override fun onClick() {
        super.onClick()
        binding.apply {
            refresh.onClick {
                drawerLayout.closeDrawer(navigationView)
                getProgress(this@MainActivity)
                UIKit.postDelayed({
                    getEventList()
                    hindProgress()
                }, 1000)
            }
            search.onClick {
                if (isLogin()) {
                    start(SearchActivity::class.java)
                }
            }
            header.onClick {
                showTipDialog(
                    getString(R.string.sure_logout),
                    getString(R.string.cancel),
                    getString(R.string.sure)
                ) {
                    logout()
                }
            }
            headerM.onClick {
                showTipDialog(
                    getString(R.string.sure_logout),
                    getString(R.string.cancel),
                    getString(R.string.sure)
                ) {
                    logout()
                }
            }
            headerM1.onClick {
                signIn()
            }
            editBtn.onClick {
                closeClick()
                start(AddActivity::class.java) {
                    putExtra("EventListBean", eventEdit)
                }
            }
            delBtn.onClick {
                if (isLogin()) {
                    showTipDialog(
                        getString(R.string.del_sure), getString(R.string.cancel),
                        getString(R.string.sure)
                    ) {
                        getProgress(this@MainActivity)
                        deleteCalendarEvent(eventId) {
                            if (it == 1) {
                                closeClick()
                                hindProgress()
                                getEventList()
                            }
                        }
                    }
                }
            }
            open1.onClick {
                if (isLogin()) {
                    open1.isSelected = !open1.isSelected
                    changeCalendarSet(this@MainActivity, 1, open1.isSelected) {
                        getEventList()
                    }
                }
            }
            open2.onClick {
                if (isLogin()) {
                    open2.isSelected = !open2.isSelected
                }
            }
            open3.onClick {
                if (isLogin()) {
                    open3.isSelected = !open3.isSelected
                    changeCalendarSet(this@MainActivity, 3, open3.isSelected) {
                        getEventList()
                    }
                }
            }
            open4.onClick {

                open4.isSelected = !open4.isSelected
                SPUtil.setSp(Tool.showHoliday, open4.isSelected)
                changeCalendarSet(this@MainActivity, 4, open4.isSelected) {
                    getEventList()
                }

            }
            addTask.onClick {
                if (isLogin()) {
                    addTaskDialog()
                }
            }
            add.onClick {
                if (isLogin()) {
                    start(TypeManage::class.java) {
                        putExtra("list", CALENDARS_LIST)
                    }
                }
            }
            setting.onClick {
                drawerLayout.closeDrawer(navigationView)
                settingDialog {
                    when (it) {
                        1 -> {
                            if (isLogin()) {
                                showActDialog {}
                            }
                        }

                        2 -> {
                            if (isLogin()) {
                                start(SetOneActivity::class.java)
                            }
                        }

                        3 -> {
                            showHolidayDialog()
                        }

                        4 -> {
                            showAppDialog()
                        }

                        5 -> {
                            logout()
                        }
                    }

                }
            }
            help.onClick {
                showHelpDialog { }
            }
            schedule.onClick {
                val localDate = LocalDate()
                val yearStr =
                    if (lastdate.year == localDate.year) "" else lastdate.year.toString() + ""
                monthName.text = lastdate.toString("MMMM") + " " + yearStr
                calender.setCurrentmonth(lastdate)
                calender.adjustheight()
                mIsExpanded = false
                appBar.setExpanded(false, false)
               // LiveDataBus.get().with("msgEvent").value = MessageEvent(lastdate)
                monthviewpager.gone()
                yearviewpager.gone()
                weekviewcontainer!!.gone()
                mNestedView!!.visible()
                val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
                (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(true)
                appBar.elevation = 20f
                arrowImageView.visible()
                drawerLayout.closeDrawer(Gravity.LEFT)
            }
            dayViewItem.onClick {
                weekviewcontainer!!.visible()
                monthviewpager.gone()
                yearviewpager.gone()
                mNestedView!!.gone()
                mWeekView!!.numberOfVisibleDays = 1
                mWeekView!!.textSize = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_SP,
                    12f,
                    resources.displayMetrics
                ).toInt()
                mWeekView!!.eventTextSize = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_SP,
                    12f,
                    resources.displayMetrics
                ).toInt()
                mWeekView!!.allDayEventHeight = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    26f,
                    resources.displayMetrics
                ).toInt()
                val todaydate = Calendar.getInstance()
                todaydate[Calendar.DAY_OF_MONTH] = lastdate.dayOfMonth
                todaydate[Calendar.MONTH] = lastdate.monthOfYear - 1
                todaydate[Calendar.YEAR] = lastdate.year
                mWeekView!!.goToDate(todaydate)
                val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
                (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(true)
                appBar.elevation = 0f
                arrowImageView.visible()
                drawerLayout.closeDrawer(Gravity.LEFT)
            }
            weekViewItem.onClick {
                weekviewcontainer!!.visibility = View.VISIBLE
                monthviewpager.visibility = View.GONE
                yearviewpager.visibility = View.GONE
                mNestedView!!.visibility = View.GONE
                mWeekView!!.numberOfVisibleDays = 7
                mWeekView!!.textSize = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_SP,
                    12f,
                    resources.displayMetrics
                ).toInt()
                mWeekView!!.eventTextSize = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_SP,
                    12f,
                    resources.displayMetrics
                ).toInt()
                mWeekView!!.allDayEventHeight = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    20f,
                    resources.displayMetrics
                ).toInt()
                val todaydate = Calendar.getInstance()
                todaydate[Calendar.DAY_OF_MONTH] = lastdate.dayOfMonth
                todaydate[Calendar.MONTH] = lastdate.monthOfYear - 1
                todaydate[Calendar.YEAR] = lastdate.year
                mWeekView!!.goToDate(todaydate)
                val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
                (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(true)
                appBar.elevation = 0f
                arrowImageView.visibility = View.VISIBLE
                drawerLayout.closeDrawer(Gravity.LEFT)
            }
            monthViewItem.onClick {
                appBar.setExpanded(false, false)
                mNestedView!!.gone()
                weekviewcontainer!!.gone()
                yearviewpager.gone()
                monthviewpager.visible()
                val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
                (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(false)
                appBar.elevation = 0f
                arrowImageView.invisible()
                drawerLayout.closeDrawer(Gravity.LEFT)
                monthName.text = lastdate.toString("MMM")
                monthviewpager.setCurrentItem(
                    calender.calculateCurrentMonth(lastdate),
                    true
                )
            }
            yearViewItem.onClick {
                appBar.setExpanded(false, false)
                mNestedView!!.gone()
                weekviewcontainer!!.gone()
                yearviewpager.visible()
                monthviewpager.gone()
                val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
                (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(false)
                appBar.elevation = 0f
                arrowImageView.invisible()
                drawerLayout.closeDrawer(Gravity.LEFT)
                monthName.text = lastdate.year.toString() + ""
                yearviewpager.setCurrentItem(lastdate.year % 2000, false)
            }
            toNow.onClick {
                val localDate = LocalDate.now()
                if (yearviewpager.visibility == View.VISIBLE && yearviewpager.adapter != null) {
                    yearviewpager.setCurrentItem(localDate.year % 2000, false)
                } else {
                    if (monthviewpager.visibility == View.VISIBLE && monthviewpager.adapter != null) {
                        monthviewpager.setCurrentItem(
                            calender.calculateCurrentMonth(localDate), false
                        )
                    }
                    if (weekviewcontainer!!.visibility == View.VISIBLE) {
                        val today = Calendar.getInstance()
                        today[Calendar.DAY_OF_MONTH] = localDate.dayOfMonth
                        today[Calendar.MONTH] = localDate.monthOfYear - 1
                        today[Calendar.YEAR] = localDate.year
                        mWeekView!!.goToDate(today)
                    }
                    val linearLayoutManager = mNestedView!!.layoutManager as LinearLayoutManager
                    mNestedView!!.stopScroll()
                    val local =
                        LocalDate(localDate.year, localDate.monthOfYear, localDate.dayOfMonth)
                    indextrack.forEach {
                        if (it.localDate == local) {
                            if (isAppBarExpanded()) {
                                calender.setCurrentmonth(LocalDate())
                                expandedfirst = it.p
                                topspace = 20
                                linearLayoutManager.scrollToPosition(it.p)
                                LiveDataBus.get().with("monthChangeEvent").value =
                                    MonthChange(localDate, 0)
                                month = localDate.dayOfMonth
                                lastdate = localDate
                            } else {
                                expandedfirst = it.p
                                topspace = 20
                                linearLayoutManager.scrollToPosition(it.p)
                                LiveDataBus.get().with("monthChangeEvent").value =
                                    MonthChange(localDate, 0)
                                month = localDate.dayOfMonth
                                lastdate = localDate
                            }
                        }
                    }
                }
            }
        }
    }

    private fun logout() {
        u = null
        binding.apply {
            calendarAdapter!!.models = arrayListOf()
            open1.isSelected = false
            open2.isSelected = false
            open3.isSelected = false
            open4.isSelected = false
            header1.visible()
            headerM1.visible()
            header.invisible()
            name.text = "local account"
        }
        UIKit.postDelayed({
            getEventList()
        }, 500)
        UserManager.logout(this@MainActivity)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        binding.apply {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)//侧滑栏关闭手势滑动
            if (item.itemId == android.R.id.home) {
                drawerLayout.openDrawer(navigationView)
                return true
            }
            if (item.itemId == R.id.action_favorite) {
                val localDate = LocalDate.now()
                if (yearviewpager.isVisible && yearviewpager.adapter != null) {
                    yearviewpager.setCurrentItem(localDate.year % 2000, false)
                } else {
                    if (monthviewpager.isVisible && monthviewpager.adapter != null) {
                        monthviewpager.setCurrentItem(
                            calender.calculateCurrentMonth(localDate),
                            false
                        )
                    }
                    if (weekviewcontainer!!.isVisible) {
                        val todayDate = Calendar.getInstance()
                        todayDate[Calendar.DAY_OF_MONTH] = localDate.dayOfMonth
                        todayDate[Calendar.MONTH] = localDate.monthOfYear - 1
                        todayDate[Calendar.YEAR] = localDate.year
                        mWeekView!!.goToDate(todayDate)
                    }
                    val linearLayoutManager = mNestedView!!.layoutManager as LinearLayoutManager?
                    mNestedView!!.stopScroll()
                    val lo = LocalDate(
                        localDate.year,
                        localDate.monthOfYear,
                        localDate.dayOfMonth
                    )
                    indextrack.forEach {
                        if (it.localDate == lo) {
                            if (isAppBarExpanded()) {
                                calender.setCurrentmonth(LocalDate())
                                expandedfirst = it.p
                                topspace = 20
                                linearLayoutManager!!.scrollToPosition(it.p)
                                LiveDataBus.get().with("monthChangeEvent").value =
                                    MonthChange(localDate, 0)
                                month = localDate.dayOfMonth
                                lastdate = localDate
                            } else {
                                expandedfirst = it.p
                                topspace = 20
                                linearLayoutManager!!.scrollToPosition(it.p)
                                LiveDataBus.get().with("monthChangeEvent").value =
                                    MonthChange(localDate, 0)
                                month = localDate.dayOfMonth
                                lastdate = localDate
                            }
                        }
                    }
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

    open fun closeClick() {
        binding.apply {
            closebtn.gone()
            eventName.gone()
            roundrect.gone()
            eventRange.gone()
            holiday.gone()
            eventTime.gone()
            if (eventview != null) {
                val animWidth = ValueAnimator.ofInt(getDevicewidth(), eventview!!.width)
                animWidth.addUpdateListener { valueAnimator ->
                    val va = valueAnimator.animatedValue as Int
                    val lay: ViewGroup.LayoutParams = redlay.layoutParams
                    lay.width = va
                    redlay.layoutParams = lay
                }
                animWidth.setDuration(300)
                val animHeight = ValueAnimator.ofInt(getDeviceHeight(), 0)
                animHeight.addUpdateListener { valueAnimator ->
                    val va = valueAnimator.animatedValue as Int
                    val lay: ViewGroup.LayoutParams = redlay.layoutParams
                    lay.height = va
                    redlay.layoutParams = lay
                    if (redlay.translationZ != 0f && valueAnimator.animatedFraction > 0.7) {
                        val shape = GradientDrawable()
                        shape.cornerRadius =
                            resources.getDimensionPixelSize(R.dimen.fourdp).toFloat()
                        shape.setColor(mycolor)
                        redlay.background = shape
                        redlay.translationZ = 0f
                        shadow.gone()
                    }
                }
                animHeight.setDuration(300)
                val animX = ValueAnimator.ofFloat(0f, eventview!!.left.toFloat())
                animX.addUpdateListener { valueAnimator ->
                    val va = valueAnimator.animatedValue as Float
                    redlay.translationX = va
                }
                animX.setDuration(300)
                val aniMy = ValueAnimator.ofFloat(0f, (fullview!!.top + toolbar.height).toFloat())
                aniMy.addUpdateListener { valueAnimator ->
                    val va = valueAnimator.animatedValue as Float
                    redlay.translationY = va
                }
                aniMy.setDuration(300)
                animWidth.start()
                animHeight.start()
                aniMy.start()
                animX.start()
            }
        }
    }

    private fun setupDateTimeInterpreter(shortDate: Boolean) {
        mWeekView!!.dateTimeInterpreter = object : DateTimeInterpreter {
            override fun interpretday(date: Calendar): String {
                val weekdayNameFormat = SimpleDateFormat("EEE", Locale.getDefault())
                var weekday = weekdayNameFormat.format(date.time)
                val format = SimpleDateFormat(" M/d", Locale.getDefault())
                // All android api level do not have a standard way of getting the first letter of
                // the week day name. Hence we get the first char programmatically.
                // Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657
                if (mWeekView!!.numberOfVisibleDays == 7) weekday = weekday[0].toString()
                return weekday.uppercase(Locale.getDefault())
            }

            override fun interpretDate(date: Calendar): String {
                val dayOfMonth = date[Calendar.DAY_OF_MONTH]
                return dayOfMonth.toString() + ""
            }

            override fun interpretTime(hour: Int): String {
                return if (hour > 11) (hour - 12).toString() + " PM" else if (hour == 0) "12 AM" else "$hour AM"
            }
        }
    }

    private fun setExpandAndCollapseEnabled(enabled: Boolean) {
        if (mNestedView!!.isNestedScrollingEnabled != enabled) {
            ViewCompat.setNestedScrollingEnabled(mNestedView!!, enabled)
        }
    }

    @SuppressLint("SetTextI18n")
    open fun selectDateFromMonthPager(year: Int, month: Int, day: Int) {
        lastdate = LocalDate(year, month, day)
        val localDate = LocalDate()
        val yearStr = if (lastdate.year == localDate.year) "" else lastdate.year.toString() + ""
        binding.apply {
            monthName.text = "${lastdate.toString("MMMM")} $yearStr"
            calender.setCurrentmonth(lastdate)
            calender.adjustheight()
            mIsExpanded = false
            appBar.setExpanded(false, false)
            LiveDataBus.get().with("msgEvent").value = MessageEvent(LocalDate(year, month, day))
            monthviewpager.gone()
            yearviewpager.gone()
            mNestedView!!.visible()
            val layoutParams = appBar.layoutParams as CoordinatorLayout.LayoutParams
            (layoutParams.behavior as MyAppBarBehavior?)!!.setScrollBehavior(true)
            appBar.elevation = 20f
            arrowImageView.visible()
        }
    }


    inner class MonthPageAdapter(
        fragmentManager: FragmentManager?,
        val monthModels: java.util.ArrayList<MonthModel>,
        private val height: Int
    ) : FragmentStatePagerAdapter(fragmentManager!!) {
        override fun getCount(): Int {
            return monthModels.size
        }

        // Returns the fragment to display for that page
        override fun getItem(position: Int): Fragment {
            return MonthFragment.newInstance(
                monthModels[position].month,
                monthModels[position].year,
                monthModels[position].firstday,
                monthModels[position].dayModelArrayList,
                eventList, height, montheventlist
            )
        }
    }


    inner class DateAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>(),
        StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder?> {
        var today: LocalDate = LocalDate.now()
        private val weekStr = arrayOf("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")
        fun getEventAllList(): ArrayList<EventModel> {
            return eventalllist
        }

        override fun getItemViewType(position: Int): Int {
            if (position > 1 && eventalllist[position].type == 0 &&
                getHeaderId(position) == getHeaderId(position - 1)
            ) return 0
            if (position > 1 && eventalllist[position].type == 3 &&
                eventalllist[position - 1].type == 1
            ) return 3
            if (position + 1 < eventalllist.size && eventalllist[position]
                    .type == 3 && (eventalllist[position + 1]
                    .type == 1 || eventalllist[position + 1].type == 0)
            ) return 3
            return eventalllist[position].type
        }

        private fun getHeaderItemViewType(position: Int): Int {
            return eventalllist[position].type
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return when (viewType) {
                0 -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.view_item, parent, false)
                    ItemViewHolder(view)
                }

                1 -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.viewlast, parent, false)
                    EndViewHolder(view)
                }

                2 -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.noplanlay, parent, false)
                    NoplanViewHolder(view)
                }

                3 -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.rangelayextrabottomspace, parent, false)
                    RangeViewHolder(view)
                }

                else -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.rangelayextrabottomspace, parent, false)
                    RangeViewHolder(view)
                }
            }
        }

        override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
            when (getItemViewType(position)) {
                0 -> {
                    val holder = viewHolder as ItemViewHolder
                    val color = eventalllist[position].color
                    val sp = SPUtil.getSp(Tool.holidayColor, Tool.color)
                    holder.eventtextview.setBackgroundColor(
                        if (color == -2) Color.parseColor(sp) else color
                    )
                    holder.eventtextview.text = eventalllist[position].eventname
                    if (position + 1 < eventalllist.size && eventalllist[position].localDate == today
                        && (eventalllist[position + 1].localDate != today)
                    ) {
                        holder.circle.visible()
                        holder.line.visible()
                    } else {
                        holder.circle.gone()
                        holder.line.gone()
                    }
                }

                1 -> {
                    val holder = viewHolder as EndViewHolder
                    holder.eventimageview.setImageResource(
                        monthreSource[eventalllist[position].localDate.monthOfYear - 1]
                    )
                    holder.monthname.text = eventalllist[position].localDate.toString("MMMM YYYY")
                        .replace("start", "")
                        .replace("eventView", "")
                }

                2 -> {
                    val holder = viewHolder as NoplanViewHolder
                    holder.noPlan.onClick {
                        if (isLogin()) {
                            start(AddActivity::class.java)
                        }
                    }
                }

                else -> {
                    val holder = viewHolder as RangeViewHolder
                    holder.rangetextview.text =
                        eventalllist[position].eventname
                            .replace("weekView", "")
                            .replace("eventView", "")
                }
            }
        }

        override fun getHeaderId(position: Int): Long {
            return when (eventalllist[position].type) {
                1, 3 -> position.toLong()
                else -> {
                    val localDate: LocalDate = eventalllist[position].localDate
                    val un = localDate.dayOfMonth + localDate.monthOfYear + localDate.year
                    un.toLong()
                }
            }
        }

        override fun onCreateHeaderViewHolder(
            parent: ViewGroup,
            position: Int
        ): RecyclerView.ViewHolder {
            val type = getHeaderItemViewType(position)
            return when {
                type == 2 -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.todayheader, parent, false)
                    object : RecyclerView.ViewHolder(view) {}
                }

                type == 0 -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.headerview, parent, false)
                    object : RecyclerView.ViewHolder(view) {}
                }

                else -> {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.empty, parent, false)
                    object : RecyclerView.ViewHolder(view) {}
                }
            }
        }

        override fun onBindHeaderViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
            val type = getHeaderItemViewType(position)
            if (type == 2) {
                val varView = holder!!.itemView.findViewById<TextView>(R.id.tvToday)
                val dateView = holder.itemView.findViewById<TextView>(R.id.tvTodayNum)
                if (varView != null && dateView != null) {
                    varView.text = weekStr[eventalllist[position].localDate.dayOfWeek - 1]
                    dateView.text = eventalllist[position].localDate.dayOfMonth.toString()
                    holder.itemView.tag = position
                }
            } else if (type == 0) {
                val varView = holder!!.itemView.findViewById<TextView>(R.id.eventHeader)
                val dateView = holder.itemView.findViewById<TextView>(R.id.eventHeaderNum)
                if (varView != null && dateView != null) {
                    varView.text = weekStr[eventalllist[position].localDate.dayOfWeek - 1]
                    dateView.text = eventalllist[position].localDate.dayOfMonth.toString()
                    holder.itemView.tag = position
                }
            }
        }

        override fun getItemCount(): Int {
            return eventalllist.size
        }

        internal inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var eventtextview: TextView
            var circle: View
            var line: View

            init {
                eventtextview = itemView.findViewById(R.id.item_event_name)
                eventtextview.setOnClickListener(View.OnClickListener { v ->
                    binding.apply {
                        if (isAppBarExpanded()) {
                            mIsExpanded = !mIsExpanded
                            mNestedView!!.stopScroll()
                            appBar.setExpanded(mIsExpanded, true)
                            return@OnClickListener
                        }
                        var eventInfo: EventInfo? = null
                        eventList.forEach {
                            if (eventalllist[adapterPosition].id == it.event.id) {
                                eventInfo = it.event
                                eventEdit = it
                            }
                        }
                        if (eventInfo != null) {
                            eventId = eventInfo!!.id.toLong()
                            holiday.text = eventInfo!!.info.pk()
                            editBtn.isVisible = eventInfo!!.accountname ==
                                    CALENDARS_NAME || eventInfo!!.accountname.contains("diy#")
                            delBtn.isVisible = editBtn.isVisible
                            eventName.text = if (eventInfo!!.accountname.contains("diy#"))
                                eventInfo!!.accountname.split("diy#")[1] else eventInfo!!.accountname
                            eventRange.text = eventInfo!!.title.pk(getString(R.string.no_info))
                            eventAddress.isVisible = !eventInfo!!.address.isNullOrEmpty()
                            eventAddress.text = eventInfo!!.address
                            if (!eventInfo!!.isallday) {
                                val p: String =
                                    eventInfo!!.starttime.format(PATTERN_DATE)
                                val start: String =
                                    eventInfo!!.starttime.format(PATTERN_HOUR_MINUTE)
                                val end: String =
                                    eventInfo!!.endtime.format(PATTERN_HOUR_MINUTE)
                                val ss = "$p $start-$end"
                                eventTime.text = ss
                            } else {
                                val localDate = LocalDate(eventInfo!!.starttime)
                                val today: LocalDate = LocalDate.now()
                                if (localDate.year == today.year) {
                                    val range = localDate.toString("MMM-dd")
                                    eventTime.text = range
                                } else {
                                    val range = localDate.toString("MMM-dd, YYYY")
                                    eventTime.text = range
                                }
                            }
                        }
                        closebtn.gone()
                        eventName.gone()
                        roundrect.gone()
                        eventRange.gone()
                        holiday.gone()
                        eventTime.gone()
                        val view = mNestedView!!.layoutManager!!.findViewByPosition(adapterPosition)
                        val layoutParams: ViewGroup.LayoutParams = redlay.layoutParams
                        layoutParams.height = v.height
                        layoutParams.width = v.width
                        redlay.layoutParams = layoutParams
                        redlay.translationX = v.left.toFloat()
                        redlay.translationY = (view!!.top + toolbar.height).toFloat()
                        redlay.translationZ = 0f
                        mycolor = eventalllist[adapterPosition].color
                        roundrect.setBackgroundColor(mycolor)
                        val animwidth = ValueAnimator.ofInt(redlay.width, getDevicewidth())
                        animwidth.addUpdateListener { valueAnimator ->
                            val va = valueAnimator.animatedValue as Int
                            val lay: ViewGroup.LayoutParams = redlay.layoutParams
                            lay.width = va
                            redlay.layoutParams = lay
                        }
                        animwidth.setDuration(300)
                        val animHeight = ValueAnimator.ofInt(redlay.height, getDeviceHeight())
                        animHeight.addUpdateListener { valueAnimator ->
                            val va = valueAnimator.animatedValue as Int
                            val lay: ViewGroup.LayoutParams = redlay.layoutParams
                            lay.height = va
                            redlay.layoutParams = lay
                            if (redlay.translationZ == 0f && valueAnimator.animatedFraction > 0.15) {
                                redlay.setBackgroundColor(Color.WHITE)
                                shadow.visible()
                                redlay.translationZ =
                                    resources.getDimensionPixelSize(R.dimen.tendp).toFloat()
                            }
                        }
                        animHeight.setDuration(300)
                        val animX = ValueAnimator.ofFloat(redlay.translationX, 0f)
                        animX.addUpdateListener { valueAnimator ->
                            val va = valueAnimator.animatedValue as Float
                            redlay.translationX = va
                        }
                        animX.setDuration(300)
                        val animY = ValueAnimator.ofFloat(redlay.translationY, 0f)
                        animY.addUpdateListener { valueAnimator ->
                            val va = valueAnimator.animatedValue as Float
                            redlay.translationY = va
                        }
                        animY.setDuration(300)
                        animHeight.addListener(object : AnimatorListenerAdapter() {
                            override fun onAnimationEnd(animation: Animator) {
                                super.onAnimationEnd(animation)
                                Handler().postDelayed({
                                    closebtn.visible()
                                    eventName.visible()
                                    roundrect.visible()
                                    eventRange.visible()
                                    holiday.visible()
                                    eventTime.visible()
                                }, 150)
                            }
                        })
                        animwidth.start()
                        animHeight.start()
                        animY.start()
                        animX.start()
                        eventview = v
                        fullview = view
                    }
                })
                circle = itemView.findViewById(R.id.circle)
                line = itemView.findViewById(R.id.line)
            }
        }

        internal inner class EndViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var eventimageview: ScrollParallaxImageView
            var monthname: TextView

            init {
                eventimageview = itemView.findViewById(R.id.imageView)
                eventimageview.setParallaxStyles(VerticalMovingStyle())
                monthname = itemView.findViewById(R.id.textView11)
            }
        }

        internal inner class NoplanViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var noPlan: TextView

            init {
                noPlan = itemView.findViewById(R.id.noPlan)
            }
        }

        internal inner class RangeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var rangetextview: TextView

            init {
                rangetextview = itemView.findViewById(R.id.view_range_textview)
            }
        }
    }

    override fun onMonthChange(newYear: Int, newMonth: Int): MutableList<out WeekViewEvent> {
        if (!isgivepermission) return java.util.ArrayList()
        val initial = LocalDate(newYear, newMonth, 1)
        val length = initial.dayOfMonth().maximumValue
        val events: MutableList<WeekViewEvent> = java.util.ArrayList()
        for (i in 1..length) {
            val localDate = LocalDate(newYear, newMonth, i)
            var contains = false
            for (event in eventList) {
                if (event.data == localDate) {
                    contains = true
                }
            }
            if (contains) {
                var eventInfo: EventInfo? = null
                for (event in eventList) {
                    if (event.data == localDate) {
                        eventInfo = event.event
                    }
                }
                if (i == 1) {
                    eventList.forEach {
                        if (it.data == localDate) {
                            val containEvent = HashMap<String, String>()
                            var movecheck: EventInfo? = it.event
                            var newobj = EventInfo(movecheck)
                            eventInfo = newobj
                            containEvent[movecheck!!.id.toString()] = "1"
                            while (movecheck!!.nextnode != null) {
                                movecheck = movecheck.nextnode
                                newobj.nextnode = EventInfo(movecheck)
                                newobj = newobj.nextnode
                                containEvent[movecheck.id.toString()] = "1"
                            }
                            val infolist: MutableList<EventInfo?> =
                                java.util.ArrayList<EventInfo?>()
                            var originalevent: EventInfo? = null
                            for (event in eventList) {
                                if (event.data == localDate) {
                                    originalevent = event.event
                                }
                            }
                            while (originalevent != null) {
                                if (!containEvent.containsKey(originalevent.id.toString())) {
                                    infolist.add(originalevent)
                                }
                                originalevent = originalevent.nextnode
                            }
                            for (eventInfo1 in infolist) {
                                newobj.nextnode = EventInfo(eventInfo1)
                                newobj = newobj.nextnode
                            }
                        }
                    }
                }
                while (eventInfo != null) {
                    val startTime: Calendar =
                        Calendar.getInstance(TimeZone.getTimeZone(eventInfo!!.timezone))
                    if (eventInfo!!.isalreadyset) {
                        startTime.timeInMillis =
                            localDate.toDateTimeAtStartOfDay(DateTimeZone.forTimeZone(startTime.timeZone)).millis
                    } else {
                        startTime.timeInMillis = eventInfo!!.starttime
                    }
                    val endTime =
                        Calendar.getInstance(TimeZone.getTimeZone(eventInfo!!.timezone)) as Calendar
                    endTime.timeInMillis = eventInfo!!.endtime
                    val enddate = LocalDate(endTime)
                    val maxdate = LocalDate(newYear, newMonth, length)
                    if (enddate.isAfter(maxdate)) {
                        val localDateTime = LocalDateTime(newYear, newMonth, length, 23, 59, 59)
                        val f = if (eventInfo!!.isallday) 0 else 1000
                        endTime.timeInMillis = localDateTime.toDateTime().millis + 1000
                    }
                    Log.e("title:" + eventInfo!!.title, LocalDate(eventInfo!!.starttime).toString())
                    val dau: Int = Days.daysBetween(
                        LocalDate(eventInfo!!.endtime),
                        LocalDate(eventInfo!!.starttime)
                    ).days
                    val event = WeekViewEvent(
                        eventInfo!!.id.toLong(),
                        eventInfo!!.title,
                        startTime,
                        endTime,
                        eventInfo!!.accountname,
                        eventInfo!!.info
                    )
                    event.myday = eventInfo!!.noofdayevent
                    event.isAllDay = eventInfo!!.isallday
                    event.color = eventInfo!!.eventcolor
                    //                    if (eventInfo.isallday)event.setColor(getResources().getColor(R.color.event_color_04));
//                    else event.setColor(getResources().getColor(R.color.event_color_02));
                    events.add(event)
                    eventInfo = eventInfo!!.nextnode
                }
            }
        }
        return events
    }

    private var eventId = -1L
    private var eventEdit: EventListBean? = null
    override fun onEventClick(event: WeekViewEvent?, eventRect: RectF?) {
        eventId = event!!.id
        binding.apply {
            if (isAppBarExpanded()) {
                mIsExpanded = !mIsExpanded
                mNestedView!!.stopScroll()
                appBar.setExpanded(mIsExpanded, true)
                return
            }
            eventName.text = event.accountname
            eventRange.text = event.name.pk(getString(R.string.no_info))
            eventAddress.isVisible = !event.location.isNullOrEmpty()
            eventAddress.text = event.location
            if (!event.isAllDay) {
                if (event.noofday > 1) {
                    val p: String =
                        event.startTime.format(PATTERN_DATE)
                    val start: String =
                        event.startTime.format(PATTERN_HOUR_MINUTE)
                    val end: String =
                        event.endTime.format(PATTERN_HOUR_MINUTE)
                    val ss = "$p $start-$end"
                    eventTime.text = ss
                }
            } else {
                val localDate = LocalDate(event.startTime)
                val today: LocalDate = LocalDate.now()
                if (localDate.year == today.year) {
                    val range = localDate.toString("MMM-dd")
                    eventTime.text = range
                } else {
                    val range = localDate.toString("MMM-dd, YYYY")
                    eventTime.text = range
                }
            }

            editBtn.isVisible = event.accountname ==
                    CALENDARS_NAME || event.accountname.contains("diy#")
            delBtn.isVisible = editBtn.isVisible
            holiday.text = event.info
            closebtn.visible()
            eventName.gone()
            roundrect.gone()
            eventRange.gone()
            holiday.gone()
            eventTime.gone()
            val view = View(this@MainActivity)
            val layoutParams1 = ViewGroup.LayoutParams(
                eventRect!!.width().toInt(), eventRect.height().toInt()
            )
            view.left = eventRect.left.toInt()
            view.top = eventRect.top.toInt()
            view.right = eventRect.right.toInt()
            view.bottom = eventRect.bottom.toInt()
            view.layoutParams = layoutParams1
            redlay.visible()
            val layoutParams: ViewGroup.LayoutParams = redlay.layoutParams
            layoutParams.height = eventRect.height().toInt()
            layoutParams.width = eventRect.width().toInt()
            redlay.layoutParams = layoutParams
            redlay.translationX = eventRect.left
            redlay.translationY = eventRect.top + toolbar.height
            if (event.color != 0) {
                val shape = GradientDrawable()
                shape.cornerRadius = resources.getDimensionPixelSize(R.dimen.fourdp).toFloat()
                mycolor = event.color
                shape.setColor(mycolor)
                redlay.background = shape
                roundrect.background = shape
            } else {
                val shape = GradientDrawable()
                shape.cornerRadius = resources.getDimensionPixelSize(R.dimen.fourdp).toFloat()
                mycolor = Color.parseColor(Tool.color)
                shape.setColor(mycolor)
                redlay.background = shape
                roundrect.background = shape
            }

            //  GradientDrawable drawable = (GradientDrawable) holder.eventtextview.getBackground();
//               if (eventalllist.get(position).getType()==0)drawable.setColor(eventalllist.get(position).getColor());
//               else drawable.setColor(Color.BLACK);
            //  GradientDrawable drawable = (GradientDrawable) holder.eventtextview.getBackground();
//               if (eventalllist.get(position).getType()==0)drawable.setColor(eventalllist.get(position).getColor());
//               else drawable.setColor(Color.BLACK);
            redlay.translationZ = 0f

            val animWidth = ValueAnimator.ofInt(redlay.width, getDevicewidth())
            animWidth.addUpdateListener { valueAnimator ->
                val va = valueAnimator.animatedValue as Int
                val lay: ViewGroup.LayoutParams = redlay.layoutParams
                lay.width = va
                redlay.layoutParams = lay
            }
            animWidth.setDuration(300)
            val animHeight = ValueAnimator.ofInt(redlay.height, getDeviceHeight())
            animHeight.addUpdateListener { valueAnimator ->
                val va = valueAnimator.animatedValue as Int
                val lay: ViewGroup.LayoutParams = redlay.layoutParams
                lay.height = va
                redlay.layoutParams = lay
                if (redlay.translationZ == 0f && valueAnimator.animatedFraction > 0.2) {
                    redlay.setBackgroundColor(Color.WHITE)
                    shadow.visible()
                    redlay.translationZ = resources.getDimensionPixelSize(R.dimen.tendp).toFloat()
                }
            }
            animHeight.setDuration(300)
            val animx = ValueAnimator.ofFloat(redlay.translationX, 0f)
            animx.addUpdateListener { valueAnimator ->
                val va = valueAnimator.animatedValue as Float
                redlay.translationX = va
            }
            animx.setDuration(300)

            val animY = ValueAnimator.ofFloat(redlay.translationY, 0f)
            animY.addUpdateListener { valueAnimator ->
                val va = valueAnimator.animatedValue as Float
                redlay.translationY = va
            }
            animY.setDuration(300)
            animHeight.addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    super.onAnimationEnd(animation)
                    Handler().postDelayed({
                        closebtn.visible()
                        eventName.visible()
                        roundrect.visible()
                        eventRange.visible()
                        holiday.visible()
                        eventTime.visible()
                    }, 150)
                }
            })
            animWidth.start()
            animHeight.start()
            animY.start()
            animx.start()
            eventview = view
            fullview = view
        }
    }

    override fun onEventLongPress(event: WeekViewEvent?, eventRect: RectF?) {
        showTipDialog(
            getString(R.string.del_sure),
            getString(R.string.cancel),
            getString(R.string.sure)
        ) {
            getProgress(this@MainActivity)
            deleteCalendarEvent(eventId) {
                if (it == 0) {
                    getEventList()
                }
                hindProgress()
            }
        }
    }

    private fun getEventTitle(time: Calendar): String? {
        return String.format(
            "Event of %02d:%02d %s/%d",
            time[Calendar.HOUR_OF_DAY],
            time[Calendar.MINUTE], time[Calendar.MONTH] + 1,
            time[Calendar.DAY_OF_MONTH]
        )
    }

    override fun onEmptyViewLongPress(time: Calendar?) {
        //toast("Empty view long pressed: " + getEventTitle(time!!))
    }

    @SuppressLint("SetTextI18n")
    override fun onFirstVisibleDayChanged(
        newFirstVisibleDay: Calendar?,
        oldFirstVisibleDay: Calendar?
    ) {
        if (!weekviewcontainer!!.isVisible || !isgivepermission) return
        if (isAppBarClosed()) {
            val localDate = LocalDate(
                newFirstVisibleDay!![Calendar.YEAR],
                newFirstVisibleDay[Calendar.MONTH] + 1,
                newFirstVisibleDay[Calendar.DAY_OF_MONTH]
            )
            lastdate = localDate
            val year =
                if (localDate.year == LocalDate.now().year) "" else
                    localDate.year.toString()
            binding.apply {
                if (monthName.text != localDate.toString("MMM") + " " + year) {
                    lastdate = localDate
                    calender.setCurrentmonth(localDate)
                    calender.adjustheight()
                    mIsExpanded = false
                    appBar.setExpanded(false, false)
                    monthName.text = localDate.toString("MMM") + " " + year
                }
            }
            // EventBus.getDefault().post(new MessageEvent(new LocalDate(monthModel.getYear(),monthMo.getMonth(),1)));
            // if (monthChangeListner!=null)monthChangeListner.onmonthChange(myPagerAdapter.monthModels.get(position));
        } else {
            //  binding.setCurrentmonth(i);
        }

    }

    override fun isAppBarIdle(): Boolean {
        return mAppBarIdle
    }

    override fun isAppBarExpanded(): Boolean {
        return mAppBarOffset == 0
    }

    override fun isAppBarClosed(): Boolean {
        return isappbarclosed;
    }

    override fun appbaroffset(): Int {
        return expandedfirst
    }

    private fun getEventList() {
        eventList = arrayListOf<EventListBean>()
        binding.open4.isSelected = SPUtil.getSp(Tool.showHoliday, true)
        val event = CalendarUtils.getCalendar(this@MainActivity, binding.open4.isSelected)
        eventList = event ?: arrayListOf()
        binding.apply {
            calendarAdapter!!.models = CALENDARS_LIST
            open1.isSelected = ACTIVITY_SHOW
            open2.isSelected = ACTIVITY_SHOW
            open3.isSelected = BIRTHDAY_SHOW
            montheventlist = java.util.HashMap()
            calender.init(eventList)
            calender.setCurrentmonth(LocalDate())
            calender.adjustheight()
            if (eventList.isNotEmpty()) {
                eventList.forEach {
                    if (it.event.noofdayevent > 1) {
                        var nextmonth = it.data.plusMonths(1).withDayOfMonth(1)
                        val enddate = LocalDate(it.event.endtime)
                        while (enddate.isAfter(nextmonth)) {
                            if (montheventlist!!.containsKey(nextmonth)) {
                                var firstday: Int =
                                    nextmonth.dayOfMonth().withMinimumValue().dayOfWeek().get()
                                if (firstday == 7) firstday = 0
                                val noofdays: Int =
                                    Days.daysBetween(nextmonth, enddate).getDays() + firstday
                                val eventInfo = it.event
                                val newobj = EventInfo()
                                newobj.title = eventInfo.title
                                newobj.timezone = eventInfo.timezone
                                newobj.isallday = eventInfo.isallday
                                newobj.eventcolor = eventInfo.eventcolor
                                newobj.endtime = eventInfo.endtime
                                newobj.accountname = eventInfo.accountname
                                newobj.isalreadyset = true
                                newobj.starttime = eventInfo.starttime
                                newobj.noofdayevent = noofdays
                                newobj.id = eventInfo.id
                                val beginnode = montheventlist!![nextmonth]
                                newobj.nextnode = beginnode
                                montheventlist!![nextmonth] = newobj
                            } else {
                                var firstday: Int =
                                    nextmonth.dayOfMonth().withMinimumValue().dayOfWeek().get()
                                if (firstday == 7) firstday = 0
                                val noofdays: Int =
                                    Days.daysBetween(nextmonth, enddate).getDays() + firstday
                                val newobj = EventInfo()
                                val eventInfo = it.event
                                newobj.title = eventInfo.title
                                newobj.timezone = eventInfo.timezone
                                newobj.accountname = eventInfo.accountname
                                newobj.isallday = eventInfo.isallday
                                newobj.eventcolor = eventInfo.eventcolor
                                newobj.endtime = eventInfo.endtime
                                newobj.isalreadyset = true
                                newobj.starttime = eventInfo.starttime
                                newobj.noofdayevent = noofdays
                                newobj.id = eventInfo.id
                                montheventlist!![nextmonth] = newobj
                            }
                            nextmonth = nextmonth.plusMonths(1).withDayOfMonth(1)
                        }
                    }
                }
            }
            isgivepermission = true
            lastdate = LocalDate()
            calender.setCurrentmonth(LocalDate())
            calender.adjustheight()
            mIsExpanded = false
            appBar.setExpanded(false, false)
            mWeekView!!.notifyDatasetChanged()
        }
    }

    private fun isLogin(): Boolean {
        if (u == null) {
            showTipDialog(
                getString(R.string.login_in), getString(R.string.cancel),
                getString(R.string.sure)
            ) {
                signIn()
            }
        }
        return u != null
    }

    //以下为谷歌
    private fun signIn() {
        getProgress(this)
        val signInIntent: Intent = MApplication.get().mGoogle!!.signInIntent
        startActivityForResult(signInIntent, Tool.RESULTCODE_SUCCESS)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Tool.RESULTCODE_SUCCESS) {
            //谷歌登录回调
            hindProgress()
            val task: Task<GoogleSignInAccount> =
                GoogleSignIn.getSignedInAccountFromIntent(data)
            handleSignInResult(task)
        }
    }

    //GoogleSignInAccount 对象包含已登录用户的相关信息，例如用户的姓名。
    @SuppressLint("SuspiciousIndentation")
    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            val account = completedTask.getResult(ApiException::class.java)
            scopeNetLife {
                val loginApi = loginApi(account.idToken.pk())
                if (loginApi.code == 1) {
                    updateUI(account, "")
                }
            }
        } catch (e: ApiException) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            toast(getString(R.string.login_error))
        }
    }

    private fun updateUI(account: GoogleSignInAccount?, token: String) {
        if (account != null) {
            UserManager.save(
                UserBean(
                    account.id.pk(),
                    token,
                    account.idToken.pk(),
                    account.account!!.type,
                    if (account.photoUrl == null) "" else account.photoUrl.toString(),
                    account.displayName.pk(),
                    account.familyName.pk(),
                    account.email.pk(),
                    account.account!!.name
                )
            )
            u = UserManager.get()
            InitNet.initNetHttp(this, token)
            showUser(u)
            UIKit.postDelayed({ getEventList() }, 1000)
        }
    }

    private fun showUser(u: UserBean?) {
        if (u != null) {
            CALENDARS_NAME = u.email
            binding.apply {
                if (u.avatar.isEmpty()) {
                    header1.visible()
                    headerM1.visible()
                    header1.text = u.familyName
                    headerM1.text = u.familyName
                } else {
                    headerM1.gone()
                    header1.gone()
                    header.load(u.avatar.pk())
                    headerM.load(u.avatar.pk())
                }
                name.text = u.username.pk()
            }
        }
    }

    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
            if (binding.closebtn.isVisible) {
                closeClick()
            } else {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    toast(getString(R.string.again_to_exit))
                    exitTime = System.currentTimeMillis()
                } else {
                    BaseApplication.get().exit()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}